package com.bardsoftware.foronuvolo.server;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bardsoftware.foronuvolo.client.AnswersViewUI;
import com.bardsoftware.foronuvolo.client.StartDiscussionService;
import com.bardsoftware.foronuvolo.data.Discussion;
import com.bardsoftware.foronuvolo.data.DiscussionTag;
import com.bardsoftware.foronuvolo.data.FeedForListening;
import com.bardsoftware.foronuvolo.data.ForumUser;
import com.bardsoftware.foronuvolo.data.PMF;
import com.google.gwt.user.client.Window;
import com.sun.cnpi.rss.elements.Item;
import com.sun.cnpi.rss.elements.PubDate;
import com.sun.cnpi.rss.elements.Rss;
import com.sun.cnpi.rss.parser.RssParser;
import com.sun.cnpi.rss.parser.RssParserException;
import com.sun.cnpi.rss.parser.RssParserFactory;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;



//TODO delete RSS!!!!

public class CheckNewsServlet extends HttpServlet {	
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
		throws ServletException,IOException {
		Collection<FeedForListening> feeds = FeedForListening.getAllFeeds();	
		for(FeedForListening feed : feeds) {								
			try {
				SyndFeed f = new SyndFeedInput().build(new XmlReader(new URL(feed.getFeedURL())));				
				for(Object obj : f.getEntries()) {
					SyndEntry entry = (SyndEntry) obj;
					if(entry.getPublishedDate().after(feed.getLastUpd())) {						
						for(String id : feed.getSubscribers()) {
							ForumUser author = ForumUser.find(id);
							if(author != null) {
								ArrayList<String> tags = new ArrayList<String>();
								tags.add(DiscussionTag.RSS_TAG.getName());
								Discussion d = new Discussion(author,"=" + entry.getTitle() + "=\n" + entry.getLink(),tags);
								d.save();
								DiscussionsViewPage.resetDiscussionViewPageCache();
							}
						}
						feed.setLastUpdate(new Date());
						feed.save();
					}					
				}
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FeedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}							
		}
	}
}
